package com.ps.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ps.context.BaseContext;
import com.ps.entity.AddressBook;
import com.ps.mapper.AddressBookMapper;
import com.ps.service.AddressBookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {



    public List<AddressBook> list(AddressBook addressBook) {
       return lambdaQuery()
               .eq(addressBook.getUserId()!=null,AddressBook::getUserId, addressBook.getUserId())
                .eq( addressBook.getPhone()!=null,AddressBook::getPhone, addressBook.getPhone())
                .eq( addressBook.getIsDefault()!=null,AddressBook::getIsDefault, addressBook.getIsDefault())
                .list();
    }

    public void saveaddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        save(addressBook);
    }

    public AddressBook getById(Long id) {
        AddressBook book = query().eq("id", id).one();
        return book;
    }

    public void update(AddressBook addressBook) {
       lambdaUpdate()
               .eq(AddressBook::getId,addressBook.getId())
               .update(addressBook);
    }

    @Transactional
    public void setDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        lambdaUpdate()
                .set(AddressBook::getIsDefault, addressBook.getIsDefault())
                .eq(AddressBook::getUserId, BaseContext.getCurrentId())
                .update();
        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        lambdaUpdate()
                .set(AddressBook::getIsDefault,addressBook.getIsDefault())
                .eq(AddressBook::getId,addressBook.getId())
                .update();
    }

    public void deleteById(Long id) {
        removeById(id);
    }
}
